package com.chookss.tiku

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.chookss.R
import com.chookss.Urls
import com.chookss.tiku.entity.Subject
import com.chookss.tools.MyEvent
import com.chookss.tools.MyToast
import com.chookss.tools.NavigationTools
import com.chookss.tools.Utils
import com.johnrambo.ktea.ktExtends.observe
import errorToast
import infoToast
import kotlinx.android.synthetic.main.activity_practice_test_base.*
import kotlinx.android.synthetic.main.view_subject.*
import org.greenrobot.eventbus.EventBus
import successToast
import toast
import java.util.*

/**
 * Company:
 * Project:
 * Author: liuhaoge
 * Date: 2020/12/28 09:30
 * Note:
 */
abstract class BasePracticeTestActivity<T : BasePracticeTestViewModel> : BaseSubjectActivity<T>() {
    var sourceType: String = ""
    protected var startTime = 0L
    override fun subjectView() = subjectView
    var isShowAnswer: Boolean = false  //是否有答案模式

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_practice_test_base)
        initState()
//        sourceType=intent.getStringExtra("practiceType")
        ivLeft.setOnClickListener {
            onBackPressed()
        }
        tvSubmit.setOnClickListener {
            submitMyAnswer(false)
        }
        btnNext.setOnClickListener {
            gotoSubject(subjectIndex + 1)
        }


        btnPrev.setOnClickListener {
            if (subjectIndex > 0) {
                gotoSubject(subjectIndex - 1)
            } else {
                infoToast("已经是第一题了")
            }
        }

        updateCollectBtnState(false)
        tvCollect.setOnClickListener { collectSubject() }
        tvShare.setOnClickListener { shareSubject() }
        tvError.setOnClickListener {
            if (subjectView != null) {
                if (subjectView.subject != null) {
                    var subject = subjectView.subject!!
                    var intent = Intent(this, FeedbackActivity::class.java)
                    intent.putExtra("subjectCode", subject.subjectCode)
                    startActivity(intent)
                }
            }
        }
        NavigationTools.setWaterMark(this, "1")
        initRv()
    }

    fun initRv() {
//        rvSubject.setLayoutManager(LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false))
//        rvSubject.addItemDecoration(RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), resources.getColor(R.color.line_gray)))
//     rvType.setLayoutManager(LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false))
//        rvMemory.addItemDecoration(RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), resources.getColor(R.color.line_gray)))
//         rvType.setLayoutManager(LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false))
//         rvMemory.addItemDecoration(RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), resources.getColor(R.color.line_gray)))
//        val map: HashMap<String, String> = HashMap()
//        map.put("title","单选题")
//        map.put("select","false")
//        subjectList.add(map)
//        val map2: HashMap<String, String> = HashMap()
//        map2.put("title","多选题")
//        map2.put("select","false")
//        subjectList.add(map2)
//        val map3: HashMap<String, String> = HashMap()
//        map3.put("title","判断题")
//        map3.put("select","false")
//        subjectList.add(map3)
//         val typeMap: HashMap<String, String> = HashMap()
//         typeMap.put("title","全部")
//         typeMap.put("select","false")
//         typeList.add(typeMap)
//         val typeMap2: HashMap<String, String> = HashMap()
//         typeMap2.put("title","智能练习")
//         typeMap2.put("select","false")
//         typeList.add(typeMap2)
//         val typeMap3: HashMap<String, String> = HashMap()
//         typeMap3.put("title","专项练习")
//         typeMap3.put("select","false")
//         typeList.add(typeMap3)
//         val typeMap4: HashMap<String, String> = HashMap()
//         typeMap4.put("title","模拟卷")
//         typeMap4.put("select","false")
//         typeList.add(typeMap4)
//         val typeMap5: HashMap<String, String> = HashMap()
//         typeMap5.put("title","考试")
//         typeMap5.put("select","false")
//         typeList.add(typeMap5)
//         val memoryMap: HashMap<String, String> = HashMap()
//         memoryMap.put("title","未记忆")
//         memoryMap.put("select","false")
//         memoryList.add(memoryMap)
//         val memoryMap2: HashMap<String, String> = HashMap()
//         memoryMap2.put("title","开始记忆")
//         memoryMap2.put("select","false")
//         memoryList.add(memoryMap2)
//         val memoryMap3: HashMap<String, String> = HashMap()
//         memoryMap3.put("title","正在巩固")
//         memoryMap3.put("select","false")
//         memoryList.add(memoryMap3)
//         val memoryMap4: HashMap<String, String> = HashMap()
//         memoryMap4.put("title","已牢记")
//         memoryMap4.put("select","false")
//         memoryList.add(memoryMap4)
//         val memoryMap5: HashMap<String, String> = HashMap()
//         memoryMap5.put("title","开始遗忘")
//         memoryMap5.put("select","false")
//         memoryList.add(memoryMap5)
//         val memoryMap6: HashMap<String, String> = HashMap()
//         memoryMap6.put("title","已遗忘")
//         memoryMap6.put("select","false")
//         memoryList.add(memoryMap6)
//         subjectAdapter = TitleAdapter(R.layout.item_subject_choice, this, subjectList)
//         rvSubject.setAdapter(subjectAdapter)
//         typeAdapter = TitleAdapter(R.layout.item_subject_choice, this, typeList)
//         rvSubject.setAdapter(typeAdapter)
//         memoryAdapter = TitleAdapter(R.layout.item_subject_choice, this, memoryList)
//         rvSubject.setAdapter(memoryAdapter)
        ivSubjectShaixuan.setOnClickListener {
            rlType.visibility = View.VISIBLE
            rvSubject.visibility = View.VISIBLE
        }
        ivTypeShaixuan.setOnClickListener {
            rlType.visibility = View.VISIBLE
            rvType.visibility = View.VISIBLE
        }
        ivMemory.setOnClickListener {
            rlType.visibility = View.VISIBLE
            rvMemory.visibility = View.VISIBLE
        }
        rlType.setOnClickListener {
            rlType.visibility = View.GONE
            rvSubject.visibility = View.GONE
            rvType.visibility = View.GONE
            rvMemory.visibility = View.GONE
        }
//         subjectAdapter!!.setOnItemClickListener { adapter, view, position ->
//             if(subjectList.get(position).get("select").equals("true")){
//                 subjectList.get(position).put("select","false")
//             }else{
//                 subjectList.get(position).put("select","true")
//             }
//             adapter.notifyDataSetChanged()
//             rlType.visibility= View.GONE
//             rvSubject.visibility= View.GONE
//         }
//         typeAdapter!!.setOnItemClickListener { adapter, view, position ->
//             if(typeList.get(position).get("select").equals("true")){
//                 typeList.get(position).put("select","false")
//             }else{
//                 typeList.get(position).put("select","true")
//             }
//             adapter.notifyDataSetChanged()
//             rlType.visibility= View.GONE
//             rvType.visibility= View.GONE
//         }
//         memoryAdapter!!.setOnItemClickListener { adapter, view, position ->
//             if(memoryList.get(position).get("select").equals("true")){
//                 memoryList.get(position).put("select","false")
//             }else{
//                 memoryList.get(position).put("select","true")
//             }
//             adapter.notifyDataSetChanged()
//             rlType.visibility= View.GONE
//             rvMemory.visibility= View.GONE
//         }
    }

    fun shareSubject() {
        if (Urls.antiShake.check()) {
            return
        }
        if (subjectView != null) {
            if (subjectView.subject == null) {
                return
            }
            var subject = subjectView.subject!!
            val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            clipboardManager?.setPrimaryClip(ClipData.newPlainText("", subject.subjectCode))
            toast(subject.subjectCode + " 已复制到剪切板")
        }
    }

    private fun collectSubject() {
        if (Urls.antiShake.check()) {
            return
        }
        if (subjectView != null) {
            if (subjectView.subject == null) {
                return
            }
            var subject = subjectView.subject!!
            if (subject.collectFlag == "1") {
                viewModel.unCollectSubject(subject, sourceType).observe(this, {
                    if (it.error != null) {
                        errorToast(it.error.message ?: "")
                    } else {
                        successToast("已取消收藏")
                        updateCollectBtnState(false)
                        var map: HashMap<String, String> = HashMap()
                        map.put("subjectCode",subject.subjectCode)
                        map.put("collectFlag", "0")
                        EventBus.getDefault().post(MyEvent(map))
                        refreshSubject()
                    }
                })
            } else {
                viewModel.collectSubject(subject, sourceType).observe(this, {
                    if (it.error != null) {
                        errorToast(it.error.message ?: "")
                    } else {
                        successToast("已收藏")
                        var map: HashMap<String, String> = HashMap()
                        map.put("subjectCode",subject.subjectCode)
                        map.put("collectFlag", "1")
                        EventBus.getDefault().post(MyEvent(map))
                        updateCollectBtnState(true)
                    }
                })
            }
        }
    }

    private fun updateCollectBtnState(selected: Boolean) {
        tvCollect.isSelected = selected
        tvCollect.text = if (selected) "取消" else "收藏"
    }

    override fun onSubjectLoaded(index: Int, subject: Subject) {
        startTime = System.currentTimeMillis()
        updateCollectBtnState(subject.collectFlag == "1")

    }

    fun submitMyAnswer(isBeiti: Boolean) {
        if (subjectView != null) {
            Utils.hideInputKeyboard(this, subjectView)
        }
        if (subjectView.subject == null) {
            return
        }
        if (!isBeiti) {

            if (subjectView.subject?.subjectTypeCode.equals("1004") || subjectView.subject?.subjectTypeCode.equals(
                    "1005"
                )
            ) {
                for (i in 0 until subjectView.myAnswers.size) {
                    if (Utils.isNull(subjectView.myAnswers.get(i))) {
                        MyToast.show("请先答题，再提交")
                        return;
                    }
                }
            } else {
                if (subjectView.myAnswers.size == 0) {
                    MyToast.show("请先答题，再提交")
                    return
                }
            }


            var time = System.currentTimeMillis() - startTime
            loadingProgress.show()
            viewModel.submitAnswer(subjectView.subject!!, subjectView.myAnswers, time)
                .observe(this, {
                    loadingProgress.dismiss()
                    if (it.error != null) {
                        errorToast(it.error.message ?: "")
                    } else {
//                    tvDone.text = "今日练习: ${it.data.totalNum}题"
//                    tvRightRatio.text = "正确率: ${it.data.rightRatio}%"
                        subjectView.subject?.isRight = it.data.toString()
                        getSubjectDetailParse()
                    }
                })

        } else {
            viewModel.getSubjectDetail(subjectView.subject!!)
                .observe(this, {
                    loadingProgress.dismiss()
                    if (it.error != null) {
                        errorToast(it.error.message ?: "")
                    } else {
                        subjectView.showRightAnswerInfo()
                        onAnswerSubmited(
                            subjectIndex,
                            subjectView.subject!!,
                            subjectView.myAnswers
                        )
                        isShowAnswer = true
                        subjectView.showAnswerDetail(it.data)
                    }
                })
        }
    }

    fun getSubjectDetailParse() {
        if (subjectView != null) {
            if (subjectView.subject == null) {
                return
            }
            viewModel.getSubjectDetail(subjectView.subject!!)
                .observe(this, {
                    loadingProgress.dismiss()
                    if (it.error != null) {
                        errorToast(it.error.message ?: "")
                    } else {
                        subjectView.showRightAnswerInfo()
                        onAnswerSubmited(
                            subjectIndex,
                            subjectView.subject!!,
                            subjectView.myAnswers
                        )
                        isShowAnswer = true
                        subjectView.showAnswerDetail(it.data)
                    }
                })
        }
    }

    class TitleAdapter(
        layoutResId: Int,
        context: Context,
        data: ArrayList<HashMap<String, String>>
    ) : BaseQuickAdapter<HashMap<String, String>, BaseViewHolder>(layoutResId, data) {

        override fun convert(holder: BaseViewHolder, item: HashMap<String, String>) {
            val ivStatus = holder?.getView<ImageView>(R.id.ivStatus)
            val tvTiltle = holder?.getView<TextView>(R.id.tvTiltle)
            tvTiltle?.text = item?.get("title")
            if (item?.get("select").equals("true")) {
                tvTiltle?.isSelected = true
                ivStatus?.isSelected = true
            } else {
                tvTiltle?.isSelected = false
                ivStatus?.isSelected = false
            }
        }

    }

    open fun onAnswerSubmited(subjectIndex: Int, subject: Subject, myAnswers: List<String>) {

    }

    override fun onDestroy() {
        super.onDestroy()
        if (subjectView != null) {
            Utils.hideInputKeyboard(this, subjectView)
        }
    }
}